

import NotAuth from "@@/view/NotAuth"
import { isAdmin } from "@@/utils/index"
import NotFound from "@@/view/NotFound"
import { Navigate, useLocation } from "react-router-dom"


// 路由拦截
// https://www.bilibili.com/video/BV1XR4y1D7Vp
// https://www.bilibili.com/video/BV1XR4y1D7Vp


// 非常优秀的路由鉴权
// https://www.bilibili.com/video/BV1Rv4y1T7aV/
// https://oh-router.netlify.app/zh/guide/navigation


// 原生react-router 路由鉴权
// https://www.bilibili.com/video/BV1g54y137H3/


const adminRouters = ['/dashboard/users/add', '/dashboard/users/list']


// 包装的嵌套路由组建
const AuthRouterWrapper = (props) => {
    const access_token = localStorage.getItem("access_token")


    const {pathname} = useLocation()
    console.log('pathname==', pathname)

    if("/" === pathname) {
        return <Navigate to="/dashboard" />
    }

    // 解决重定向无限递归的问题
    if("/login" === pathname) {
        if(access_token) {
            return <Navigate to="/dashboard" />
        }

        return props.children
    }

    if(!access_token) {
        return <Navigate to="/login" />
    } else {

        let admin = isAdmin()
        // console.log('admin==', admin,  adminRouters.includes(pathname))

        if(!admin && adminRouters.includes(pathname)) {
            return <NotAuth />
        }

        return (
            props.children
        )
    }
    
    
}



export default AuthRouterWrapper
